package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class DelMRitem
 */ 
public class ManipulateGridEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridEnv() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String strSQL = "";
		String oper = request.getParameter("oper");			//增刪改查那一種
		String bssId = "MBMS";
		String subSysId = request.getParameter("subSysId");
		String envId = "";
		String result = "";
		String currentUser = "842297";
		
		
		
		/** 判別需進行何種操作 **/
		if ( "del".equalsIgnoreCase(oper) ) {
			envId = request.getParameter("id");
			strSQL = "DELETE FROM env WHERE envid=? AND bssid=? AND subsysid=?";
			try {
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, envId);
				ps.setString(2, bssId);
				ps.setString(3, subSysId);
				ps.execute();
				
				wid.keepLogProfile(wid.ENV, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+envId;
			} catch (SQLException e) {
				result = "刪除"+envId+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		} else if ( "add".equalsIgnoreCase(oper) ) {
			
			envId = request.getParameter("envid");
			subSysId = request.getParameter("subSysId");
			
			try {
				if ( !isDuplicated(bssId,subSysId,envId,conn,ps,rs) ) {
					strSQL = "INSERT INTO env (subsysid,envname,creator,createdDateTime,bssid,envid) VALUES (?,?,?,?,?,?)";
					String envName = request.getParameter("envname");
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, subSysId);
					ps.setString(2, envName);
					ps.setString(3, currentUser);
					ps.setTimestamp(4, wid.currentTimeStamp());
					ps.setString(5, bssId);
					ps.setString(6, envId);
					ps.execute();
					
					wid.keepLogProfile(wid.ENV, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+envId;
				} else {
					result = envId+" 已存在 !";		
				}
			} catch (SQLException e) {
				result = "新增"+envId+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		} else if ( "edit".equalsIgnoreCase(oper) ) {
			envId = request.getParameter("id");
			subSysId = request.getParameter("subsysid");
			String orisubsysid = request.getParameter("orisubsysid");
			String envName = request.getParameter("envname");
			strSQL = "UPDATE env SET envname=?,subsysid=?,lastUpdator=?,lastUpdatedDateTime=? WHERE subsysid=? AND bssid=? AND envid=?";
			try {
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, envName);
				ps.setString(2, subSysId);
				ps.setString(3, currentUser);
				ps.setTimestamp(4, wid.currentTimeStamp());
				ps.setString(5, orisubsysid);
				ps.setString(6, bssId);
				ps.setString(7, envId);
				ps.execute();
				
				wid.keepLogProfile(wid.ENV, wid.UPDATE, currentUser, conn, ps);
				result = "修改完成 "+envId;

			} catch (SQLException e) {
				result = "修改"+envId+"失敗!!\n\n";
				result += wid.errProcess(e);
			}
		}

		try {
			if (rs!= null) {rs.close();}
			if (ps!= null) {ps.close();}
			if (conn!= null) {conn.close();}
		} catch (SQLException e) {
			System.out.println(wid.errProcess(e));
		}
		
		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(result);		
	}
	
	private boolean isDuplicated(String bssId,String subSysId,String envId,Connection conn,PreparedStatement ps, ResultSet rs) throws SQLException {
		String strSQL = "SELECT COUNT(*) FROM env WHERE bssid=? AND subsysid=? AND envid=?";
		
		ps = conn.prepareStatement(strSQL);
		ps.setString(1, subSysId);
		ps.setString(2, bssId);
		ps.setString(3, envId);
		rs = ps.executeQuery();
		rs.next();

		return rs.getInt(1) == 0?false:true;
	}
	
}